package aimis.repo;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import aimis.domain.Department;
import java.util.List;

public interface DepartmentRepo extends JpaRepository<Department, Long> {
    @Query("""
            select department from Department as department where 
             :name is null or department.name like %:name%
            """)
    Page<Department> findByQuery(String name, Pageable pageable);
    @Query("""
            select department from Department as department where 
             (:name is null or department.name like %:name%) and (department.root=:root)
            """)
    Page<Department> findByQuery(String name,Department root, Pageable pageable);
    Department findByName(String name);
    Department findByNameAndParent(String name, Department parent);
    List<Department> findByParentId(Long parentId);
    @Query("""
            select department from Department as department where 
             department.root = :root
            """)
    List<Department> findByRoot(Department root);
    @Query("select department from Department as department where department.parent is null")
    Page<Department> getAllRootDepartment(Pageable pageable);
    @Query("select department from Department as department where department.parent is null and department.root=:root")
    Page<Department> getAllRootDepartment(Department root, Pageable pageable);
    @Query("select department from Department as department where department.parent is null")
    List<Department> getAllRootDepartment();
    @Query("select department from Department as department where department.parent is null and department.root=:root")
    List<Department> getAllRootDepartment(Department root);

    @Query("select department from Department as department where department.parent is null and department.name=:name")
    Department getRootDepartmentByName(String name);

    // 同一层级，同一个根 根据名字查找
    @Query("""
    select department from Department as department where (department.parent=:parent and department.name=:name and department.root=:root) 
    or (:parent is null and :root is null and department.parent is null and department.name=:name)
    """)
    Department getDepartmentByParentAndNameAndRoot(Department parent, String name, Department root);

    @Query("""
    select department from Department as department where (department.parent.name=:parentName and department.name=:name and department.root.name=:rootName) 
    """)
    Department getDepartmentByParentNameAndNameAndRootName(String parentName, String name, String rootName);
}
